import java.text.SimpleDateFormat
import com.lowagie.text.DocumentException
import com.lowagie.text.pdf.*
import groovy.json.JsonSlurper
import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import org.primefaces.PrimeFaces
import org.primefaces.event.FileUploadEvent
import org.primefaces.event.SelectEvent
import org.primefaces.model.DefaultStreamedContent
import org.primefaces.model.DefaultTreeNode
import org.primefaces.model.TreeNode
import org.primefaces.model.file.UploadedFile
import org.primefaces.util.SerializableSupplier
import wsd.appsys.sp.BackBean
import wsd.appsys.sp.SendBean
import wsd.appsys.sp.SpUtuils
import wsd.sys.jdbcManager
import wsd.sys.singlecz.singleczbean

import javax.faces.context.FacesContext
import java.awt.*
import java.text.SimpleDateFormat
import java.util.List;

public execute(o) {
    return new mc(o)
}

class mc {
    def save = true
    def start = false
    def mypara
    def dialog
    def anniu = ["查询": false, "新增": false, "修改": true, "删除": true, "保存": true, "取消": true, "增行": true, "删行": true]
    java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd")
    def currentTime = formatter.format(new Date())//当前时间
    def showCurrentTime() {
        // 创建一个SimpleDateFormat实例来指定日期时间格式
        def dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

        // 获取当前时间
        def now = new Date()

        // 使用SimpleDateFormat的format方法来格式化当前时间
        def formattedDate = dateFormat.format(now)

        // 打印格式化后的时间
        println "当前时间: $formattedDate"
    }
    public mc(f) {
        this.mypara = f;
        updateSQL()
    }
    def itemlist = [];//费用单表体查询集合
    //表头变量集合
    def datalist = [id      : null, invoice_number: null, invoice_type: null, contract_number: '', client_name: '', invoice_status: null, money_all: null,
                    reporter: null, department: null, report_time: null, auditor: null, audit_time: null, creata_time: null, def1: null, def2: null,
                    def3    : null, def4: null, def5: null, def6: null, def7: null, def8: null, def9: null, def10: null, def11: null, def12: null, def13: null,
                    def14   : null, def15: null, def16: null];
    List itemtabxz = new ArrayList<>()//多选删除表体
    def itemtremoveList = []


    def start() {
        start = true
        anniu = ["查询": true, "新增": true, "修改": true, "删除": true, "保存": false, "取消": false, "增行": false, "删行": false]
        def conn = null;
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))
            java.text.SimpleDateFormat formatterid = new java.text.SimpleDateFormat("yyyyMMdd")
            def nowtimeid = formatterid.format(new Date())//当前时间
            int maxid = getNowIdfun(nowtimeid);//获取合同编码最大值+1
            def codelen = '000'//code长度
            int strc = codelen.length() - String.valueOf(maxid).length();//获取长度差
            def code = codelen.substring(0, strc) + maxid//拼接生成当前单据id
            code = nowtimeid + code;
            println "============================" + code
            datalist = ["invoice_number": code, "report_time": currentTime,"invoice_type":"1","invoice_status":"1","money_all":200,"reporter":"刘龙","department":"销售部"]

            println datalist["invoice_number"]
        } catch (Exception e) {
            println(e.toString())
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def getNowIdfun(String tName) {
        def conn = null;
        def id = null;
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))
            def selectSql = "select id from [dbo].[Cost_TableId] where tName='" + tName + "'"
            def map = conn.firstRow(selectSql)
            if (map) {
                id = map.get("id") + 1;
                def updateSql = "update Cost_TableId set id='" + id + "' where tName='" + tName + "'"
                conn.execute(updateSql);
            } else {
                id = 1;
                def updateSql = "insert into Cost_TableId (tName,id) values ('" + tName + "',1);"
                conn.execute(updateSql);
            }
            return id;
        } catch (Exception e) {
            e.printStackTrace()
            mypara.msg("查询失败！")
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def cancel() {
        start = false
        save = true
        anniu = ["查询": false, "新增": false, "修改": true, "删除": true, "保存": true, "取消": true, "增行": true, "删行": true]
        dialog()
    }

    def insertSQL1

    def insert() {
        if (datalist["invoice_number"].toString().equals('') || datalist["invoice_number"] == null) {
            mypara.msg("单据编号为必填项")
            return
        }
        if (datalist["invoice_type"].toString().equals('0') || datalist["invoice_type"] == null) {
            mypara.msg("报销类型为必选项")
            return
        }
        if (datalist["invoice_status"].toString().equals('0') || datalist["invoice_status"] == null) {
            mypara.msg("单据状态为必选项")
            return
        }
        if (datalist["money_all"].toString().equals('') || datalist["money_all"] == null) {
            mypara.msg("费用总金额为必填项")
            return
        }
        if (datalist["reporter"].toString().equals('') || datalist["reporter"] == null) {
            mypara.msg("提报人为必填项")
            return
        }
        if (datalist["department"].toString().equals('') || datalist["department"] == null) {
            mypara.msg("提报部门为必填项")
            return
        }
        def conn = null
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))
            conn.connection.autoCommit = false;
            for (int i = 0; i < itemlist.size(); i++) {
                if (i == 0) {
                    insertSQL1 = conn.executeInsert("insert into feiyongdan (invoice_number,report_time,invoice_type,contract_number,client_name, " +
                            " invoice_status,money_all,reporter,department) values('" + datalist["invoice_number"] + "', " +
                            " '" + datalist["report_time"] + "','" + datalist["invoice_type"] + "','" + datalist["contract_number"] + "' ,'" + datalist["client_name"] + "', " +
                            " '" + datalist["invoice_status"] + "'," + datalist["money_all"] + ",'" + datalist["reporter"] + "','" + datalist["department"] + "')")
                    def insertSQL2 = "insert into feiyongdanList (id,feiyongdan_id, money_type, money, yongtu, PS) values(" + itemlist.get(i).id + "," + insertSQL1[0][0] + ", " +
                            " " + itemlist.get(i).money_type + "," + itemlist.get(i).money + ",'" + itemlist.get(i).yongtu + "' ,'" + itemlist.get(i).PS + "')"
                    conn.execute(insertSQL2)
                } else {
                    def insertSQL2 = "insert into feiyongdanList (id,feiyongdan_id, money_type, money, yongtu, PS) values(" + itemlist.get(i).id + "," + insertSQL1[0][0] + ", " +
                            " " + itemlist.get(i).money_type + "," + itemlist.get(i).money + ",'" + itemlist.get(i).yongtu + "' ,'" + itemlist.get(i).PS + "')"
                    conn.execute(insertSQL2)
                }


            }
            mypara.msg("保存成功")
            anniu = ["查询": false, "新增": false, "修改": true, "删除": true, "保存": true, "取消": true, "增行": true, "删行": true]
            conn.commit()
            dialog()
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback()
            mypara.msg("保存失败！" + e)
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def updateSQL(){
        def id = javax.faces.context.FacesContext.getCurrentInstance().getExternalContext().getSessionMap().containsKey("invoice_number");
        if (id){
            select1()
            javax.faces.context.FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("invoice_number")
        }
        println(id)
    }
    def update() {
        if (datalist["invoice_number"].toString().equals('') || datalist["invoice_number"] == null) {
            mypara.msg("单据编号为必填项")
            return
        }
        if (datalist["invoice_type"].toString().equals('0') || datalist["invoice_type"] == null) {
            mypara.msg("报销类型为必选项")
            return
        }
        if (datalist["invoice_status"].toString().equals('0') || datalist["invoice_status"] == null) {
            mypara.msg("单据状态为必选项")
            return
        }
        if (datalist["money_all"].toString().equals('') || datalist["money_all"] == null) {
            mypara.msg("费用总金额为必填项")
            return
        }
        if (datalist["reporter"].toString().equals('') || datalist["reporter"] == null) {
            mypara.msg("提报人为必填项")
            return
        }
        if (datalist["department"].toString().equals('') || datalist["department"] == null) {
            mypara.msg("提报部门为必填项")
            return
        }
        save = true
        start = false

        def conn = null
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))
            conn.connection.autoCommit = false;
            conn.execute("UPDATE feiyongdan SET   invoice_type = '" + datalist["invoice_type"] + "', contract_number = '" + datalist["contract_number"] + "', "
                    + "client_name = '" + datalist["client_name"] + "', invoice_status = '" + datalist["invoice_status"] + "', money_all = '" + datalist["money_all"] + "', reporter = '" + datalist["reporter"]
                    + "', department = '" + datalist["department"] + "', auditor = '" + datalist["auditor"] + "', audit_time = '" + datalist["audit_time"] + "' "
                    + "WHERE invoice_number = '" + datalist["invoice_number"] + "'")
            mypara.msg("修改成功")
            conn.commit()
            dialog()
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback()
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def select() {
        javax.faces.context.FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("zt", "zt");
//        javax.faces.context.FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("tbr", tbr);
//        javax.faces.context.FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("tbbm", tbbm);
//        javax.faces.context.FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("bxlx", bxlx);
//        javax.faces.context.FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("khmc", khmc);
        jdbcManager.navikzbd("/ext/fydList.xhtml", "费用单列表", "fydList");
        //javax.faces.context.FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("zt")
    }

    def select1() {
        start = true
        save = false
        anniu = ["查询": true, "新增": true, "修改": false, "删除": false, "保存": true, "取消": false, "增行": false, "删行": false]
        if (datalist["invoice_number"].toString().equals('') || datalist["invoice_number"] == null) {
            mypara.msg("单据编号为必填项")
            return
        }
        def conn = null
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))
            //conn.execute("select * from feiyongdan where invoice_number = '" + datalist["invoice_number"] + "'")

            //def chaxun = "select id, money_all from feiyongdan where invoice_number = '"+datalist["invoice_number"]+"';"
            println(1)
            def chaxun = conn.firstRow("select id,invoice_number,invoice_type, money_all ,invoice_status,reporter,department,report_time," +
                    "contract_number,client_name,auditor,audit_time from feiyongdan where invoice_number = '" + datalist["invoice_number"] + "' ")
            if (chaxun != null) {
                datalist = ["id"      : chaxun.id, "invoice_number": chaxun.invoice_number, "invoice_type": chaxun.invoice_type, "money_all": chaxun.money_all, "invoice_status": chaxun.invoice_status,
                            "reporter": chaxun.reporter, "department": chaxun.department, "report_time": chaxun.report_time, "contract_number": chaxun.contract_number, "client_name": chaxun.client_name,
                            "auditor" : chaxun.auditor, "audit_time": chaxun.audit_time]
            }
            itemlist = []
            def chaxun2 = "select id,money_type,money,yongtu,PS from feiyongdanList where feiyongdan_id in(select id  from feiyongdan where invoice_number = '" + datalist["invoice_number"] + "' )"
            conn.eachRow(chaxun2) {
                def t = ["id": it.id, "money_type": it.money_type, "money": it.money, "yongtu": it.yongtu, "PS": it.PS]
                itemlist.add(t)
                println(t)
            }
            mypara.msg("查询成功")
            conn.commit()
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }

    def delete() {
        start = false
        save = true
        if (datalist["invoice_number"].toString().equals('') || datalist["invoice_number"] == null) {
            mypara.msg("单据编号为必填项")
            return
        }
        def conn = null
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))
            conn.connection.autoCommit = false;

            conn.execute("delete feiyongdanList where feiyongdan_id=( select id from feiyongdan WHERE invoice_number =" + datalist["invoice_number"] + ")")
            conn.execute("delete feiyongdan where invoice_number=" + datalist["invoice_number"] + "")

            mypara.msg("删除成功")
            conn.commit()
            dialog()
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback()
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }


    def add() {
        def id = jdbcManager.getsqnid()
        def map = [id: id, feiyongdan_id: null, money_type: null, money: 0.00, yongtu: null, PS: null]
        itemlist.add(map);
    }

    def remove() {
        if (!itemtabxz.isEmpty()) {
            for (item in itemtabxz) {
                itemlist.remove(item);
            }
            itemtabxz.clear();
        } else {
            mypara.msg('未选择删除数据。')
        }
    }

    def remove1() {
        if (itemtabxz.size() != 0) {
            for (int i = 0; i < itemtabxz.size(); i++) {
                itemtremoveList.add(itemtabxz.get(i));
            }
            itemlist = itemlist - itemtabxz;
            itemtabxz = new ArrayList<>();
        } else {
            mypara.msg('未选择删除数据。')
        }
    }

    def gb() {
        //循环表体金额并合计
        def heji = 0
        for (int i = 0; i < itemlist.size(); i++) {
            if (itemlist[i]['money'] != null && itemlist[i]['money'] != '') {
                BigDecimal hkje = new BigDecimal("" + itemlist[i]['money'] + "")
                heji = heji + hkje
            }
        }
        datalist['money_all'] = heji
        org.primefaces.PrimeFaces.current().ajax().update("maintab:fydslist:hkje");
    }

    def dialog() {
        dialog = true
        datalist = [id      : null, invoice_number: null, invoice_type: null, contract_number: null, client_name: null, invoice_status: null, money_all: null,
                    reporter: null, department: null, report_time: null, auditor: null, audit_time: null, creata_time: null, def1: null, def2: null,
                    def3    : null, def4: null, def5: null, def6: null, def7: null, def8: null, def9: null, def10: null, def11: null, def12: null, def13: null,
                    def14   : null, def15: null, def16: null];
        itemlist = []
    }

    def execute() {
        def conn
        try {
            conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))
            del()
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close()
            }
        }
    }
    def del(){
        println "删除"
    }
}